package cn.sjtu.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 1. 关闭一些无关的防御设置
        http.csrf().disable();
        http.cors().disable();

        // 2. 关闭session
        http.sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 3. 所有路径都需要认证
        http.authorizeRequests()
                // /r/p1认证后需要p1权限才能继续访问
                .antMatchers("/r/p1").hasAnyAuthority("p1")
                // /r/p2认证后需要p2权限才能继续访问
                .antMatchers("/r/p2").hasAnyAuthority("p2")
                // 其他所有路径都不需要权限
                .anyRequest().permitAll();

        // 4. 开启表单登陆和登出
        http.formLogin()
                .defaultSuccessUrl("/hello")
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {

        // UserDetails管理器本身就是UserDetailsService
        // 管理器能够更好地管理用户信息
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user").password("$2a$10$/EShGQxL/KuEtXsVkCx/6.h.TwnWMt.dkOBObA4SynOoJ/YYmiDaG").authorities("p1").build());
        manager.createUser(User.withUsername("admin").password("$2a$10$/EShGQxL/KuEtXsVkCx/6.h.TwnWMt.dkOBObA4SynOoJ/YYmiDaG").authorities("p2").build());
        return manager;
    }
}
